<template>
    <div class="message-container">

        <div class="info">
            {{info}}
        </div>
        <hr>
        <div id="container"></div>

        <div class="bto-list">
            <van-button type="primary" @click="currentGeolocation">定位</van-button>
            <van-button type="primary" @click="search">搜索附近加油站</van-button>
            <van-button type="primary" @click="citySelected">城市选择</van-button>
        </div>

        <div class="searchResult">
            <div class="searchResult-item" v-for="(poi, index) in searchList" :key="index">
                <div class="title">{{poi.name}}</div>
                <div class="desc">地址：{{poi.address}} 电话：{{poi.tel}} 距离：{{poi.distance}}</div>
                <van-button class="driving" type="primary" @click="driving(poi)">驾车路线</van-button>
                <van-button class="driving" type="primary" @click="openGaode(poi)">打开内置高德</van-button>
            </div>
        </div>

        <div class="citySelected">
            选择的城市：<br><span style="color: red">{{city}}</span>
        </div>

    </div>
</template>

<script>
import { Button } from "vant";
let map, marker, geolocation;
export default {
    name: "Message",
    components: {
        [Button.name]: Button
    },
    data() {
        return {
            location: [113.322607693143, 23.080687120226],
            searchList: [],
            city: null,
            info: null,
        };
    },
    methods: {
        //初始化地图
        initMap() {
            let _this = this
            map = new AMap.Map("container", {
                resizeEnable: true, //是否监控地图容器尺寸变化
                zoom: 12,
                center: this.location
            });
            map.on("complete", function() {
                _this.geolocation();
            });
        },
        //定位
        geolocation() {
            let _this = this
            AMap.plugin("AMap.Geolocation", function() {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, //是否使用高精度定位，默认:true
                    timeout: 10000, //超过10秒后停止定位，默认：5s
                    buttonPosition: "RB", //定位按钮的停靠位置
                    zoomToAccuracy: true //定位成功后是否自动调整地图视野到定位点
                });
                _this.currentGeolocation()
                map.addControl(geolocation);
            });
        },
        currentGeolocation() {
            
            let _this = this
            geolocation.getCurrentPosition(function(status, result) {
                if (status == "complete") {
                    console.log("complete",result)
                    _this.info = JSON.stringify(result)

                    //先删除标记点
                    if (marker) {
                        map.remove(marker);
                    }
                    // 创建一个 Marker 实例：
                    marker = new AMap.Marker({
                        position: result.position,
                        zIndex: 11100
                    });
                    // 将创建的点标记添加到已有的地图实例：
                    marker.setMap(map);
                } else {
                    console.log("error",result)
                    _this.info = JSON.stringify(result)
                }
            });
        },
        //选择城市
        citySelected() {
            const _this = this;
            const html = document.querySelector("html");
            const fontSize = html.style.fontSize;

            AMapUI.loadUI(["misc/MobiCityPicker"], function(MobiCityPicker) {
                var cityPicker = new MobiCityPicker({
                    // 顶部城市列表
                    topGroups: [
                        {
                            id: "g1", //分组ID，需唯一
                            title: "热门城市", //分组标题
                            anchorTitle: "热", //右侧锚点标题，通常单个字符
                            adcodes: [
                                //城市的adcode列表，adcodes信息可以调用MobiCityPicker.getCityData()获取
                                "110000"
                            ]
                        },
                        {
                            id: "g2", //分组ID，需唯一
                            title: "推荐城市", //分组标题
                            anchorTitle: "热", //右侧锚点标题，通常单个字符
                            adcodes: [
                                //城市的adcode列表，adcodes信息可以调用MobiCityPicker.getCityData()获取
                                "110000"
                            ]
                        }
                    ]
                });

                //监听城市选中事件
                cityPicker.on("citySelected", function(cityInfo) {
                    //隐藏城市列表
                    cityPicker.hide();

                    //选中的城市信息
                    console.log(cityInfo);
                    _this.city = JSON.stringify(cityInfo, null, 2);
                });

                cityPicker.on("show", function() {
                    //设置 html font size 为 16px
                    html.style.fontSize = "18px";
                });
                cityPicker.on("hide", function() {
                    html.style.fontSize = fontSize;
                });

                //显示城市列表，可以用某个click事件触发
                cityPicker.show();
            });
        },

        //驾车路线
        driving(poi) {
            const _this = this;
            map.plugin("AMap.Driving", function() {
                //构造路线导航类
                var driving = new AMap.Driving({
                    map: map
                });
                driving.search(
                    new AMap.LngLat(_this.location[0], _this.location[1]),
                    new AMap.LngLat(poi.location.lng, poi.location.lat),
                    function(status, result) {
                        if (status === "complete" && result.info === "OK") {
                            const routes = result.routes[0].steps;
                            for (let item of routes) {
                                console.log(item.instruction);
                            }
                        }
                    }
                );
            });
        },
        //打开内置高德
        openGaode(poi) {
            const _this = this;
            map.plugin("AMap.Driving", function() {
                //构造路线导航类
                var driving = new AMap.Driving({
                    policy: AMap.DrivingPolicy.LEAST_TIME,
                    map: map
                });
                driving.searchOnAMAP({
                    origin: _this.location[0] + "," + _this.location[1],
                    originName: "",
                    destination: poi.location.lng + "," + poi.location.lat,
                    destinationName: poi.name
                });
            });
        },
        //周边搜索
        search() {
            console.log("开始搜索...");
            const _this = this;

            map.plugin("AMap.PlaceSearch", function() {
                var placeSearch = new AMap.PlaceSearch({
                    city: "广州", // 兴趣点城市
                    type: "餐饮服务", // 兴趣点类别
                    pageSize: 5, // 单页显示结果条数
                    pageIndex: 1, // 页码
                    citylimit: true, //是否强制限制在设置的城市内搜索
                    map: map, // 展现结果的地图实例
                    autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
                });

                var cpoint = _this.location; //中心点坐标

                //周边搜索
                placeSearch.searchNearBy("加油站", cpoint, 50000, function(
                    status,
                    result
                ) {
                    if (status === "complete" && result.info === "OK") {
                        callbackResult(result);
                    }
                });

                //周边搜索回调函数
                function callbackResult(result) {
                    const pois = result.poiList.pois;
                    pois.map((item, index) => {
                        //标记
                        var marker = new AMap.Marker({
                            map: map,
                            position: item.location,
                            label: {
                                offset: new AMap.Pixel(20, 20), //修改label相对于maker的位置
                                content: item.name
                            }
                        });

                        // 返回 p1 到 p2 间的地面距离，单位：米
                        const dis = AMap.GeometryUtil.distance(cpoint, [
                            item.location.lng,
                            item.location.lat
                        ]);
                        item = Object.assign(item, { distance: dis });
                        _this.searchList.push(item);

                        //设置标记
                        map.setCenter(marker.getPosition());
                    });
                }
            });
        }
    },

    mounted() {
        this.$nextTick(function() {
            this.initMap();
            window.addEventListener('scroll', () => {
                console.log(12)
            })
        });
    }
};
</script>


<style rel="stylesheet/scss" lang="scss" scoped>
.message-container {
    
    #container {
        width: 100%;
        height: 400px;
    }
    .bto-list {
        display: flex;
        flex-wrap: wrap;
        margin-top: 10px;
        .van-button {
            margin: 5px;
        }
    }

    .searchResult {
        &-item {
            padding: 10px 0;
            border-bottom: 1px solid #ccc;
            .desc {
                font-size: 12px;
            }
            button {
                margin-right: 10px;
            }
        }
    }
}
</style>